randn('seed',12345)
lambda = randn(1,400);
% lambda(100:200)=4+lambda(100:200);
% randn('seed',16576576576);  k=cumsum(randn(200,1)*5 ); k= k-min(k); plot(k)
lambda = lambda + sin((1:400)/20)*10+30;
lambda = [lambda];   
lambda(181:end)=0;

% a = 1;
% b = [1/4 1/4 1/4 1/4];
a = 1;
b = [1/8 1/8 1/8 1/8 1/8 1/8 1/8 1/8];
lambda_smooth = filter(b,a,lambda);

r=1; target_q=10;
x0=20; 

% prices_amz().get_hourly_price()./prices_amz().get_compute_units()

T=180;
%m=mean(lambda(:,2:T+1));
cvx_begin quiet
    variables X(1,T+1) U(1,T)  cost_r
    X(:,2:T+1) == X(:,1:T)+lambda(:,1:T)-U(:,1:T)  ; 
    X(:,1) == x0;          
    U>0;           
    cost_r==r*sum(U(:,1:T));
    minimize (sum_square(target_q*ones(1,T)-X(:,2:T+1))...
                        +cost_r)
cvx_end
Xopt=X;
Uopt=U; 
optcost = sum(sum_square(Xopt(:,2:T+1)-target_q))...
                        +r*sum(Uopt); 
fprintf('\noptcost=%d\n',optcost) ;
% subplot(3,1,1); plot(X)
% subplot(3,1,2); plot(U')
% subplot(3,1,3); plot(lambda(2:end))
% sum_square(10*ones(1,T)-X(:,2:T+1))
%cost_r

% clear
% MPC
mpccostAll=[];
for T= [180] %1:60
% T = 60; % horizon
nsteps = 180; % number of steps
n=1; m=1; 
x = x0; Xall = zeros(n,nsteps); Uall = zeros(m,nsteps);
alpha_est= 0.75;
v_cost=10; 
lambda_hat=0.1576;

for i = 1:nsteps
    fprintf('.');  
     % here I substituted lambda(:,2:T+1) with [mean(lambda(100:200)) mean(lambda(100:200))]
    lambd_prediction = lambda_hat*ones(1,T);  %  lambda_smooth(:,i:i+T-1); %lambda(:,i:i+T-1) ; % %  lambda_hat*ones(1,T) %
    cvx_begin quiet
        variables X(1,T+1) U(1,T)  cost_r 
        X(:,2:T+1) == X(:,1:T)+ lambd_prediction -U(:,1:T)  ; 
        X(:,1) == x;           
        U>0;           
        cost_r==r*sum(U(:,1:T)); 
        minimize (sum_square(target_q*ones(1,T)-X(:,2:T+1))...
                            +cost_r); 
                            %+v_cost *  (X(:,T+1)-target_q)); 
    cvx_end
    Xall(:,i) = x; u = U(:,1); Uall(:,i) = u;
    x=x+lambda(:,i)-u;   
    lambda_hat= alpha_est*lambda_hat+(1-alpha_est)*lambda(:,i+1);
end
mpccost = sum(sum_square(Xall-target_q))...
                        +r*sum(Uall); 
mpccostAll=[mpccostAll ;    mpccost];       
fprintf('\n%d\n',mpccost) ;
subplot(2,1,1); plot(Uopt); hold on; plot(Uall)
 subplot(2,1,2); plot(Xall); hold on; plot(Xopt)
 plot(lambd_prediction); hold on; plot(lambda,'--r')      
end
mpccostAll  
                
                    
 
% % subplot(4,1,1); plot(Xopt); title('Xopt') 
% % subplot(4,1,2); plot(Uopt'); title('Uopt') 
% % subplot(4,1,3); plot(Xall); title('Xall') 
% % subplot(4,1,4); plot(Uall'); title('Uall') 

 % subplot(3,1,3); plot(lambda(2:end))
kk=0







